package com.kabu.ratelimiter;

import com.google.common.util.concurrent.RateLimiter;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author jiawuwei
 * @Copyright: Copyright (c) 兆日科技股份有限公司  2020
 * @date 2020/7/29,17:12
 */
public class RateLimiterTest {
    public static void main(String[] args) {
        //限流器流速：2个请求/秒
        RateLimiter limiter =
                RateLimiter.create(4.0);
        //执行任务的线程池
        ExecutorService es = Executors
                .newFixedThreadPool(1);
        //记录上一次执行时间
        final long[] prev = {System.nanoTime()};
        //测试执行20次
        for (int i = 0; i < 20; i++) {
            //限流器限流
            limiter.acquire();
            long cur = System.nanoTime();
            //打印时间间隔：毫秒
            System.out.println(
                    (cur - prev[0]) / 1000_000);
            prev[0] = cur;
            //提交任务异步执行
//            Thread thread = new Thread(() -> {
//                long cur = System.nanoTime();
//                //打印时间间隔：毫秒
//                System.out.println(
//                        (cur - prev[0]) / 1000_000);
//                prev[0] = cur;
//            });
            //thread.start();
//            es.execute(() -> {
//                long cur = System.nanoTime();
//                //打印时间间隔：毫秒
//                System.out.println(
//                        (cur - prev[0]) / 1000_000);
//                prev[0] = cur;
//            });
        }
    }
}
